package com.itheima.mall.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.mall.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    //直接放行的url
    @Value("${gateway.excludedUrls}")
    private List<String> excludeUrls;



    /**
     * 校验token
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求链接
        String uri = exchange.getRequest().getURI().getPath();
        //判断这个uri是否可以直接放行
        if (excludeUrls.contains(uri)){
            return chain.filter(exchange);
        }

        //获取请求参数
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        //处理token
        if (StringUtils.isNotEmpty(token)){
            token = token.replace("Bearer ", "");
        }
        //判断token是否有效
        boolean verifyToken = JwtUtils.verifyToken(token);
        //校验token
        if (verifyToken){
            //4、如果token正常可用，放行
            //解析token，获取id和手机号码，
            Claims claims = JwtUtils.getClaims(token);
            String username = (String) claims.get("username");
            Integer id = (Integer) claims.get("id");

            // Admin admin = new Admin();
            // admin.setId(Long.valueOf(id));
            // admin.setUsername(username);
            // AdminHolder.set(admin);
            ServerHttpRequest request = exchange.getRequest();
            request.mutate().headers(httpHeaders -> {
                httpHeaders.add("username",username);
                httpHeaders.add("id",id.toString());
            }).build();
            //校验成功,放行
            return chain.filter(exchange);
        }
        //不成功直接滚
        ServerHttpResponse response = exchange.getResponse();
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("code", 401);
        responseData.put("message", "Unauthorized");
        return responseError(response,responseData);

    }


    //响应错误数据
    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData){
        // 将信息转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try {
            data = objectMapper.writeValueAsBytes(responseData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 输出错误信息到页面
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }


    @Override
    public int getOrder() {
        return -1;
    }

}
